<template>
  <div class="page-bg">
    <div class="main-container">
      <div class="chat-main">
        <div class="chat-container">
          <div class="chat-header">
            <div class="chat-title">
              <i class="fas fa-robot"></i>
              <div>Manus智能助手</div>
            </div>
            <div class="chat-info">您好!我是AI旅游助手,可以为您提供天气查询、车票信息查询、目的地推荐、行程规划等专业建议</div>
            <button class="new-chat-btn" @click="startNewChat">
              <i class="fas fa-plus"></i> 开启新对话
            </button>
          </div>

          <!-- 统一的消息容器 -->
          <div class="chat-messages" ref="messagesContainer">
            <div 
              v-for="(msg, index) in messages" 
              :key="msg.timestamp || index" 
              :class="['message', msg.sender || msg.type]"
            >
              <div class="avatar">
                <i :class="getAvatarIcon(msg)"></i>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <!-- 用户消息或普通AI消息 -->
                  <div v-if="msg.sender === 'user'" class="text">{{ msg.content }}</div>
                  <div v-else-if="msg.sender === 'ai'" class="text" v-html="renderMarkdown(msg.content)"></div>
                  
                  <!-- Manus特定消息类型 -->
                  <div v-else-if="msg.type === 'thinking'" class="thinking-message">
                    <div class="message-icon">💭</div>
                    <div class="message-content" v-html="renderMarkdown(msg.content)"></div>
                  </div>

                  <div v-else-if="msg.type === 'tool'" class="tool-message">
                    <div class="message-icon">🛠️</div>
                    <div class="message-content">
                      <div class="tool-header">
                        调用工具: <span class="tool-name">{{ msg.toolName }}</span>
                        <span v-if="msg.toolArguments" class="tool-arguments">(参数: {{ msg.toolArguments }})</span>
                      </div>
                      <div class="tool-result" v-if="msg.result">
                        <div class="result-label">结果:</div>
                        <div class="result-content" v-html="renderMarkdown(msg.result)"></div>
                      </div>
                    </div>
                  </div>

                  <div v-else-if="msg.type === 'step-result'" class="step-result-message">
                    <div class="step-header">
                      步骤 {{ msg.stepNumber }} 结果
                      <span class="step-status" v-if="msg.isTerminated">(任务终止)</span>
                    </div>
                    <div class="step-content" v-html="renderMarkdown(msg.content)"></div>
                  </div>

                  <div v-else-if="msg.type === 'final-result'" class="final-result-message">
                    <div class="result-header">最终结果</div>
                    <div class="result-content" v-html="renderMarkdown(msg.content)"></div>
                  </div>

                  <div v-else-if="msg.type === 'error'" class="error-message">
                    <div class="message-icon">❌</div>
                    <div class="message-content" v-html="renderMarkdown(msg.content)"></div>
                  </div>
                  
                  <div class="timestamp">{{ formatTime(msg.timestamp) }}</div>
                </div>
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoading" class="message ai">
              <div class="avatar">
                <i class="fas fa-robot"></i>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <div class="text">思考中<span class="dot-flashing"></span></div>
                </div>
              </div>
            </div>

            <!-- 进度信息 -->
            <div v-if="currentStep > 0" class="progress-info">
              <div class="progress-bar">
                <div
                    class="progress-fill"
                    :style="{ width: progressPercentage + '%' }"
                ></div>
              </div>
              <div class="step-counter">
                步骤 {{ currentStep }}/{{ maxSteps }}
              </div>
            </div>
          </div>

          <div class="input-area">
            <div class="input-container">
              <input
                  v-model="inputMessage"
                  placeholder="请输入您的问题，例如：明天从**去**的车票信息..."
                  @keyup.enter="sendMessage"
                  :disabled="isLoading"
              />
              <button
                  @click="sendMessage"
                  :class="{ disabled: !inputMessage.trim() || isLoading }"
              >
                <i class="fas fa-paper-plane"></i>
              </button>
            </div>
            <div class="input-hint">ManusAI可能会犯错误，请核对重要信息</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import {
  createManusSSEConnection,
  type SSEConnection
} from '../services/manusSseService';
import { marked } from 'marked';

// 对话数据
interface Message {
  sender?: 'user' | 'ai';
  type?: 'thinking' | 'tool' | 'step-result' | 'final-result' | 'error';
  content: string;
  timestamp?: number;
  stepNumber?: number;
  toolName?: string;
  toolArguments?: string;
  result?: string;
  isTerminated?: boolean;
}

const messages = ref<Message[]>([
  {
    sender: 'ai',
    content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
    timestamp: new Date().getTime()
  }
]);

// 用户输入
const inputMessage = ref('');

// 加载状态
const isLoading = ref(false);

// 当前步骤和最大步骤
const currentStep = ref(0);
const maxSteps = ref(10);
const progressPercentage = ref(0);

// 当前聊天ID生成函数
function getCurrentChatId() {
  return 'guest_manus_' + Date.now();
}

// 当前聊天ID
const chatId = ref(getCurrentChatId());
const messagesContainer = ref<HTMLElement | null>(null);

// 渲染Markdown内容
const renderMarkdown = (content: string) => {
  return marked.parse(content);
};

// SSE 连接引用
let sseConnection: SSEConnection | null = null;

// 获取头像图标
const getAvatarIcon = (msg: Message) => {
  if (msg.sender === 'user') return 'fas fa-user';
  if (msg.type === 'thinking') return 'fas fa-brain';
  if (msg.type === 'tool') return 'fas fa-tools';
  if (msg.type === 'error') return 'fas fa-exclamation-triangle';
  return 'fas fa-robot';
};

// 格式化时间
const formatTime = (timestamp?: number) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 开启新对话
const startNewChat = () => {
  chatId.value = getCurrentChatId();
  
  // 重置Manus相关状态
  currentStep.value = 0;
  maxSteps.value = 10;
  progressPercentage.value = 0;

  // 重置消息
  messages.value = [
    {
      sender: 'ai',
      content: '您好！我是AI旅游助手，请问您有具体的旅游目的地或行程需求吗？我可以为您提供专业的建议和行程规划。',
      timestamp: new Date().getTime()
    }
  ];
  scrollToBottom();
};

// 处理SSE事件
const handleSSEEvent = (eventType: string, data: string) => {
  switch (eventType) {
    case 'thinking':
      // 添加思考消息
      messages.value.push({
        type: 'thinking',
        content: data,
        timestamp: new Date().getTime()
      });
      break;

    case 'action':
      // 更新当前步骤
      const stepMatch = data.match(/步骤 (\d+)\/(\d+)/);
      if (stepMatch) {
        currentStep.value = parseInt(stepMatch[1]);
        maxSteps.value = parseInt(stepMatch[2]);
        progressPercentage.value = Math.round((currentStep.value / maxSteps.value) * 100);
      }

      // 检测工具调用
      const toolMatch = data.match(/调用工具: (\w+) \| 参数: (.+)/);
      if (toolMatch) {
        messages.value.push({
          type: 'tool',
          toolName: toolMatch[1],
          toolArguments: toolMatch[2],
          content: `调用工具: ${toolMatch[1]}`,
          stepNumber: currentStep.value,
          timestamp: new Date().getTime()
        });
      }
      break;

    case 'result':
      // 检测工具结果
      const toolResultMatch = data.match(/工具 (\w+) 返回结果: (.+)/);
      if (toolResultMatch) {
        // 更新最近的工具调用消息
        const lastToolIndex = messages.value.slice().reverse().findIndex(m => m.type === 'tool');
        if (lastToolIndex !== -1) {
          const realIndex = messages.value.length - 1 - lastToolIndex;
          messages.value[realIndex].result = toolResultMatch[2];
        }
      }
      // 检测步骤结果
      else if (data.includes('步骤') && data.includes('完成')) {
        messages.value.push({
          type: 'step-result',
          content: data,
          stepNumber: currentStep.value,
          timestamp: new Date().getTime()
        });
      }
      // 检测终止工具
      else if (data.includes('检测到终止工具调用')) {
        messages.value.push({
          type: 'step-result',
          content: '任务终止',
          stepNumber: currentStep.value,
          isTerminated: true,
          timestamp: new Date().getTime()
        });
      }
      // 其他结果
      else {
        messages.value.push({
          type: 'step-result',
          content: data,
          stepNumber: currentStep.value,
          timestamp: new Date().getTime()
        });
      }
      break;

    case 'error':
      messages.value.push({
        type: 'error',
        content: data,
        timestamp: new Date().getTime()
      });
      break;

    case 'finished':
      // 最终结果
      if (data.includes('任务成功完成')) {
        messages.value.push({
          type: 'final-result',
          content: '任务成功完成',
          timestamp: new Date().getTime()
        });
      }
      // 达到最大步骤
      else if (data.includes('已达到最大步骤数')) {
        messages.value.push({
          type: 'final-result',
          content: '已达到最大步骤数，任务终止',
          timestamp: new Date().getTime()
        });
      }
      // 正常结束
      else if (data.includes('任务结束')) {
        messages.value.push({
          type: 'final-result',
          content: '任务正常结束',
          timestamp: new Date().getTime()
        });
      }
      break;

    case 'complete':
      // 连接正常完成
      console.log('SSE连接正常完成');
      break;
  }

  // 滚动到底部
  scrollToBottom();
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;

  // 重置Manus相关状态
  currentStep.value = 0;
  maxSteps.value = 10;
  progressPercentage.value = 0;

  // 添加用户消息
  messages.value.push({
    sender: 'user',
    content: message,
    timestamp: new Date().getTime()
  });
  scrollToBottom();

  // 清空输入框
  inputMessage.value = '';
  isLoading.value = true;

  try {
    // 关闭现有连接（如果有）
    if (sseConnection) {
      sseConnection.close();
      sseConnection = null;
    }

    // 创建新的 SSE 连接
    sseConnection = createManusSSEConnection(
      message,
      // 消息接收回调
      (eventType, data) => {
        handleSSEEvent(eventType, data);
      },
      // 错误处理回调
      (error) => {
        console.error('SSE 连接错误:', error);
        messages.value.push({
          type: 'error',
          content: '连接出错，请重试',
          timestamp: new Date().getTime()
        });
        scrollToBottom();
      },
      // 完成回调
      () => {
        isLoading.value = false;
        sseConnection = null;
        scrollToBottom();
      }
    );

  } catch (error) {
    console.error('请求初始化失败:', error);
    messages.value.push({
      type: 'error',
      content: '请求失败，请重试',
      timestamp: new Date().getTime()
    });
    scrollToBottom();
    isLoading.value = false;
  }
};

// 滚动到底部的方法
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 监听当前步骤变化
watch(currentStep, () => {
  progressPercentage.value = Math.round((currentStep.value / maxSteps.value) * 100);
});

// 组件卸载时关闭连接
onBeforeUnmount(() => {
  if (sseConnection) {
    sseConnection.close();
  }
});

// 在mounted时初始化
onMounted(() => {
  startNewChat();
});
</script>

<style scoped>
/* 页面背景 */
.page-bg {
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  align-items: stretch;
  justify-content: flex-start;
  padding: 0;
  margin: 0;
  width: 100vw;
  max-width: 100vw;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.main-container {
  display: flex;
  flex: 1;
  width: 100%;
  max-width: 100vw;
  height: calc(100vh - 40px);
  padding: 20px 0;
  margin: 0;
  box-sizing: border-box;
  align-items: stretch;
  justify-content: flex-start;
  transition: all 0.3s ease;
  border-top: 1px solid #e5e7eb;
}

/* 聊天主区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 聊天头部 */
.chat-header {
  padding: 20px 0;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
}

.chat-title i {
  font-size: 28px;
  color: #3b82f6;
}

.chat-info {
  color: #64748b;
  font-size: 14px;
  line-height: 1.5;
}

.new-chat-btn {
  align-self: flex-start;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
  margin-top: 12px;
}

.new-chat-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.new-chat-btn i {
  font-size: 12px;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 消息样式 */
.message {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 12px 0;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f1f5f9;
  color: #64748b;
  font-size: 16px;
  flex-shrink: 0;
}

.message.user .avatar {
  background: #3b82f6;
  color: white;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.text {
  color: #1e293b;
  line-height: 1.6;
  word-wrap: break-word;
}

.text :deep(pre) {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  overflow-x: auto;
  margin: 8px 0;
}

.text :deep(code) {
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}

.text :deep(pre code) {
  background: none;
  padding: 0;
}

.text :deep(p) {
  margin: 8px 0;
}

.text :deep(ul), .text :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.text :deep(blockquote) {
  border-left: 4px solid #e2e8f0;
  margin: 8px 0;
  padding-left: 16px;
  color: #64748b;
}

/* 思考消息 */
.thinking-message {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.message-icon {
  font-size: 18px;
  flex-shrink: 0;
}

/* 工具调用消息 */
.tool-message {
  padding: 12px;
  background: #fef3c7;
  border-radius: 8px;
  border: 1px solid #fbbf24;
}

.tool-header {
  font-weight: 600;
  color: #92400e;
  margin-bottom: 8px;
}

.tool-name {
  color: #b45309;
  font-family: 'Consolas', 'Monaco', monospace;
}

.tool-arguments {
  color: #78350f;
  font-size: 13px;
}

.tool-result {
  margin-top: 8px;
}

.result-label {
  font-weight: 600;
  color: #92400e;
  margin-bottom: 4px;
}

.result-content {
  background: #fffbeb;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #fde68a;
}

/* 步骤结果消息 */
.step-result-message {
  padding: 12px;
  background: #dbeafe;
  border-radius: 8px;
  border: 1px solid #93c5fd;
}

.step-header {
  font-weight: 600;
  color: #1e40af;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.step-status {
  color: #dc2626;
  font-size: 13px;
}

.step-content {
  color: #1e3a8a;
}

/* 最终结果消息 */
.final-result-message {
  padding: 12px;
  background: #d1fae5;
  border-radius: 8px;
  border: 1px solid #6ee7b7;
}

.result-header {
  font-weight: 600;
  color: #065f46;
  margin-bottom: 8px;
}

.result-content {
  color: #047857;
}

/* 错误消息 */
.error-message {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #fee2e2;
  border-radius: 8px;
  border: 1px solid #fca5a5;
}

.error-message .message-content {
  color: #991b1b;
}

/* 时间戳 */
.timestamp {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 4px;
}

/* 加载动画 */
.dot-flashing {
  display: inline-block;
  position: relative;
  width: 4px;
  height: 4px;
  border-radius: 2px;
  background: #64748b;
  color: #64748b;
  animation: dotFlashing 1s infinite linear alternate;
  margin-left: 4px;
}

.dot-flashing::before,
.dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
  width: 4px;
  height: 4px;
  border-radius: 2px;
  background: #64748b;
  color: #64748b;
  animation: dotFlashing 1s infinite alternate;
}

.dot-flashing::before {
  left: -8px;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 8px;
  animation-delay: 0.2s;
}

@keyframes dotFlashing {
  0% {
    background: #64748b;
  }
  50%,
  100% {
    background: #cbd5e1;
  }
}

/* 进度信息 */
.progress-info {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  margin: 8px 0;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e2e8f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background: #3b82f6;
  transition: width 0.3s ease;
}

.step-counter {
  text-align: center;
  font-size: 14px;
  color: #64748b;
}

/* 输入区域 */
.input-area {
  padding: 20px 0;
  border-top: 1px solid #e5e7eb;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.input-container input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 15px;
  outline: none;
  transition: all 0.2s ease;
  background: #ffffff;
}

.input-container input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.input-container input:disabled {
  background: #f8fafc;
  cursor: not-allowed;
}

.input-container button {
  padding: 12px 16px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-container button:hover:not(.disabled) {
  background: #2563eb;
  transform: translateY(-1px);
}

.input-container button.disabled {
  background: #cbd5e1;
  cursor: not-allowed;
  transform: none;
}

.input-container button i {
  font-size: 16px;
}

.input-hint {
  text-align: center;
  font-size: 12px;
  color: #94a3b8;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    padding: 0 16px;
  }
  
  .chat-header {
    padding: 16px 0;
  }
  
  .chat-title {
    font-size: 20px;
  }
  
  .chat-title i {
    font-size: 24px;
  }
  
  .message {
    gap: 8px;
  }
  
  .avatar {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }
  
  .input-container {
    gap: 8px;
  }
  
  .input-container input {
    padding: 10px 14px;
    font-size: 14px;
  }
  
  .input-container button {
    padding: 10px 14px;
  }
}
</style>